package com.authine.cloudpivot.ext.kingdee.work;

import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.dto.kingDee.KingDeeBusiness;
import com.authine.cloudpivot.ext.dto.kingDee.request.*;
import com.authine.cloudpivot.ext.dto.voucher.RecordVoucher;
import com.authine.cloudpivot.ext.enums.kingdee.BusinessType;
import com.authine.cloudpivot.ext.enums.kingdee.FAccountIdEnum;
import com.authine.cloudpivot.ext.enums.kingdee.FormEnum;
import com.authine.cloudpivot.ext.enums.kingdee.KingDeeInvoiceApplyTypeEnum;
import com.authine.cloudpivot.ext.utils.kingdee.KingDeeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: liwei
 * @DateTime: 2021/7/16
 * @Description: TODO
 */
@Slf4j
public class InvoiceWork extends BaseWork {


    public SingleResponse createInvoiceVoucher(KingDeeInvoiceApply invoiceApply) {
        log.info("开票生成凭证  request:{}", invoiceApply);

        //发票总金额
        BigDecimal amount = invoiceApply.getAmount();
        //发票税前金额
        BigDecimal pretaxAmount = invoiceApply.getPretaxAmount();
        //税额
        BigDecimal taxPayable = invoiceApply.getTaxPayable();
        //发票申请单 id
        String id = invoiceApply.getId();
        //开票名称
        String name = invoiceApply.getName();
        //发票号码
        String number = invoiceApply.getNumber();
        //发票对应的金蝶抬头编码
        String kingdeeCode = invoiceApply.getKingdeeCode();

        //客户父组织  如果没有就获取当前组织
        String parentName = StringUtils.isBlank(invoiceApply.getParentName()) ? invoiceApply.getCompanyName() : invoiceApply.getParentName();
        //父组织匹配金蝶发票抬头编码
        String parentNameCode = getKingDeeCode(parentName);

        //根据平台税率获取 科目对应编码
        Integer subject = getTax(taxPayable);

        //摘要信息
        String remark = "发票号：" + number + "--销售--" + name;
        //转采采购金额 未税
        BigDecimal purchaseTransferPurchasePretaxAmount = invoiceApply.getPurchaseTransferPurchasePretaxAmount();

        //转采销售金额 未税
        BigDecimal saleTransferPurchasePretaxAmount = invoiceApply.getSaleTransferPurchasePretaxAmount();

        //平台销售金额 未税
        BigDecimal platformDoesNotIncludeTaxSalesAmount = invoiceApply.getPlatformDoesNotIncludeTaxSalesAmount();

        FAccountIdEnum fAccountIdEnum = FAccountIdEnum.accounts0601;
        if (invoiceApply.getContractInvoiceType()) {
            fAccountIdEnum = FAccountIdEnum.accounts060301;
        }

        List<FEntity> fEntities = new ArrayList<>();

        //应收款-云平台-贷款
        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(fAccountIdEnum.getFNumber()));
        fEntity1.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));
        fEntity1.setFDebit(amount);


        //主营业务收入-云平台-贷款
        FEntity fEntity2 = FEntity.addFentity();
        fEntity2.setFExplanation(remark);
        fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.income0601.getFNumber()));
        fEntity2.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));
        fEntity2.setFCredit(pretaxAmount);

        //应交税费-应交增值税-销项税额
        FEntity fEntity3 = FEntity.addFentity();
        fEntity3.setFExplanation(remark);
        fEntity3.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.getDes(subject)));
        fEntity3.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));
        fEntity3.setFCredit(taxPayable);

        fEntities.add(fEntity1);
        fEntities.add(fEntity2);
        fEntities.add(fEntity3);

        String remark2 = "发票号：" + id + "--结转成本--" + name;
        //既有转采 也有非转采
        if (invoiceApply.getIsTransferPurchaseAndPlatform()) {

            //发出商品 结转成本不需要区分转采非转采
            //平台金额
            BigDecimal subtract = pretaxAmount.subtract(saleTransferPurchasePretaxAmount);
            //转采和云平台总金额
            BigDecimal add = platformDoesNotIncludeTaxSalesAmount.add(purchaseTransferPurchasePretaxAmount);

            //主营业务成本-云平台
            FEntity fEntity4 = FEntity.addFentity();
            fEntity4.setFExplanation(remark2);
            fEntity4.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.main02.getFNumber()));
            fEntity4.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));
            //采购商品 不含税金额
            fEntity4.setFDebit(add);


            //发出商品-云平台
            FEntity fEntity5 = FEntity.addFentity();
            fEntity5.setFExplanation(remark2);
            fEntity5.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.release01.getFNumber()));
            fEntity5.setFDetailIdEntity(FDetailIdEntity.addDetailID6(parentNameCode));
            //采购商品不含税金额
            fEntity5.setFCredit(add);

            fEntities.add(fEntity4);
            fEntities.add(fEntity5);
        } else {

            //主营业务成本-云平台
            FEntity fEntity4 = FEntity.addFentity();
            fEntity4.setFExplanation(remark2);
            fEntity4.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.main02.getFNumber()));
            fEntity4.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));


            //发出商品-云平台 1406.01 / 发出商品-转采 1406.02
            FEntity fEntity5 = FEntity.addFentity();
            fEntity5.setFExplanation(remark2);
            fEntity5.setFDetailIdEntity(FDetailIdEntity.addDetailID6(parentNameCode));


            //是否转采
            if (invoiceApply.getIsTransfer()) {

                //发出商品-转采
                fEntity4.setFDebit(purchaseTransferPurchasePretaxAmount);

                fEntity5.setFCredit(purchaseTransferPurchasePretaxAmount);
                fEntity5.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.release02.getFNumber()));
            } else {

                //发出商品-云平台
                fEntity4.setFDebit(pretaxAmount);

                fEntity5.setFCredit(pretaxAmount);
                fEntity5.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.release01.getFNumber()));
            }
            fEntities.add(fEntity4);
            fEntities.add(fEntity5);

        }

        Integer attachments = KingDeeUtils.getAttachments(invoiceApply.getInvoiceDetailSize());

        KingDeeBusiness business = new KingDeeBusiness(id, number, BusinessType.PlatformCustomerInvoice, invoiceApply.getInvoiceTime(), attachments, invoiceApply.getAccountName());

        KingDeeEntity kingDeeEntity = getKingDeeEntity(fEntities, business);

        doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);

        log.info("开票生成凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }

    /* 平台收票生成凭证：/receive/invoice */
    public SingleResponse receiveInvoiceVoucher(KingDeeReceiveInvoice receiveInvoice) {
        log.info("平台收票生成凭证  request:{}", receiveInvoice);

        // 4.1采购暂估冲回（发票到）
        List<FEntity> temporaryList = new ArrayList<>();
        // 4.2采购发票（蓝） 增票-普票
        List<FEntity> purchaseList = new ArrayList<>();

        //确认时间
        Date confirmTime = receiveInvoice.getConfirmTime();
        //发票申请单号
        String id = receiveInvoice.getId();

        //供应商单号
        String vendorOrderId = receiveInvoice.getVendorOrderId();

        //供应商名称
        String companyName = receiveInvoice.getConfirmOrganizationCompanyName();

        //核算维度
        String confirmOrganizationId = receiveInvoice.getConfirmOrganizationId();

        //不含税金额  --不含增补
        BigDecimal pretaxAmount = receiveInvoice.getPretaxAmount().abs();
        //不含税金额  --含增补
        BigDecimal pretaxAmounts = receiveInvoice.getPretaxAmounts().abs();

        //价税
        BigDecimal amount = receiveInvoice.getAmount();

        //拼接的发票号
        String number = receiveInvoice.getNumber();

        String remark = "发票号：" + number + "--采购--" + companyName;

        //借-库存商品-云平台 1405.03
        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.stock01.getFNumber()));
        fEntity1.setFDebit(pretaxAmounts);

        purchaseList.add(fEntity1);
        //税率
        BigDecimal taxRate = receiveInvoice.getTaxRate();
        //根据税率
        Integer intoTax = getIntoTax(taxRate);
        if (null != intoTax && intoTax != 0) {
            receiveInvoice.getInvoiceRecordList().forEach(e -> {
                //4.3-贷：应交税费-应交增值税--进项税额
                FEntity fEntity2 = FEntity.addFentity();
                fEntity2.setFExplanation("发票号：" + e.getNumber() + "--采购--" + companyName);
                fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.getDes(intoTax)));
                fEntity2.setFDebit(e.getTaxPayable());
                purchaseList.add(fEntity2);

            });
        }

        //4.2-贷：应付账款-云平台-供应商    2202.03.01
        FEntity fEntity4 = FEntity.addFentity();
        fEntity4.setFExplanation(remark);
        fEntity4.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0301.getFNumber()));
        fEntity4.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(confirmOrganizationId));
        //含税金额
        fEntity4.setFCredit(amount);
        purchaseList.add(fEntity4);

        String remark2 = "供应商订单号：" + vendorOrderId + "--暂估冲回--" + companyName;
        //4.1 采购暂估冲回
        //借-库存商品 -云平台 1405.03
        FEntity fEntity5 = FEntity.addFentity();
        fEntity5.setFExplanation(remark2);
        fEntity5.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.stock01.getFNumber()));
        //不含税金额（负数）
        fEntity5.setFDebit(pretaxAmount.negate());
        temporaryList.add(fEntity5);

        //4.1-贷：应付账款-云平台-暂估应付
        FEntity fEntity6 = FEntity.addFentity();
        fEntity6.setFExplanation(remark2);
        fEntity6.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0302.getFNumber()));
        fEntity6.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(vendorOrderId));
        fEntity6.setFCredit(pretaxAmount.negate());
        temporaryList.add(fEntity6);

        purchaseList.addAll(temporaryList);
        //摘要
        String remark3 = "客户订单号：" + vendorOrderId + "--补差--";
        //增补金额
        BigDecimal add = pretaxAmounts.add(pretaxAmount.negate());
        List<FEntity> tradeList = new ArrayList<>();
        if (add.compareTo(BigDecimal.ZERO) != 0) {
            //主营业成本-云平台 5401.02
            FEntity fEntity7 = FEntity.addFentity();
            fEntity7.setFExplanation(remark3);
            fEntity7.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.main02.getFNumber()));
            fEntity7.setFDetailIdEntity(FDetailIdEntity.addFDetailID4("补差"));
            fEntity7.setFDebit(add);

            //库存商品-云平台 1405.03
            FEntity fEntity8 = FEntity.addFentity();
            fEntity8.setFExplanation(remark3);
            fEntity8.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.stock01.getFNumber()));
            fEntity8.setFCredit(add);

            tradeList.add(fEntity7);
            tradeList.add(fEntity8);

            purchaseList.addAll(tradeList);
        }

        KingDeeBusiness business = new KingDeeBusiness(id, number, BusinessType.PlatformSupplierInvoice, confirmTime, receiveInvoice.getAttachments(), receiveInvoice.getAccountName());
        KingDeeEntity kingDeeEntity = getKingDeeEntity(purchaseList, business);

        doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);

        log.info("平台收票生成凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }


    /*开红字发票生成凭证：/create/red/invoice*/
    public SingleResponse createRedInvoiceVoucher(KingDeeRedInvoiceApply invoiceApply) {
        log.info("开红字发票生成凭证  request:{}", invoiceApply);

        String numbers = invoiceApply.getNumbers();
        String kingdeeCode = invoiceApply.getKingdeeCode();
        String purchaseName = invoiceApply.getPurchaseName();

        String parentName = invoiceApply.getParentName();
        if (StringUtils.isBlank(invoiceApply.getParentName())) {
            parentName = invoiceApply.getConfirmOrganizationCompanyName();
        }

        String kingDee = getKingDeeCode(parentName);

        String companyName = invoiceApply.getConfirmOrganizationCompanyName();

        String vendorCompanyName = invoiceApply.getApplyOrganizationCompanyName();

        String vendorId = invoiceApply.getApplyOrganizationId();

        BigDecimal purchasePretaxAmount = invoiceApply.getPurchaseTransferPurchasePretaxAmount();
        BigDecimal saleTransferPurchasePretaxAmount = invoiceApply.getSaleTransferPurchasePretaxAmount();

        BigDecimal amount = invoiceApply.getAmount();
        BigDecimal pretaxAmount = invoiceApply.getPretaxAmount();


        BigDecimal platformPretaxAmount = pretaxAmount.subtract(saleTransferPurchasePretaxAmount);

        BigDecimal returnCost = platformPretaxAmount.subtract(purchasePretaxAmount);

        String remark1 = "红字发票号：" + invoiceApply.getNumber() + "--" + purchaseName + "（原发票号：" + numbers + "）";
        String remark2 = "红字发票号：" + invoiceApply.getNumber() + "--成本转回--" + purchaseName;
        if (remark2.equals(remark1)) {

        }
        // 这里判断 是客户发票红冲 还是供应商发票红冲
        if (invoiceApply.getIsRed()) {
            //  客户发票红冲
            List<FEntity> customerList = new ArrayList<>();
            //应收账款-云平台-贷款 1122.06.01
            FEntity fEntity1 = FEntity.addFentity();
            fEntity1.setFExplanation(remark1);
            fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0601.getFNumber()));
            fEntity1.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));
            fEntity1.setFDebit(amount);
            customerList.add(fEntity1);

            //主营业务收入-云平台-贷款 5001.06.01
            FEntity fEntity2 = FEntity.addFentity();
            fEntity2.setFExplanation(remark1);
            fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.income0601.getFNumber()));
            fEntity2.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));
            fEntity2.setFCredit(pretaxAmount);
            customerList.add(fEntity2);

            BigDecimal taxRate = invoiceApply.getTaxRate();
            Integer subject = getTax(taxRate);

            //应交税费-应交增值税-销项税额 2221.01.02
            FEntity fEntity3 = FEntity.addFentity();
            fEntity3.setFExplanation(remark1);
            fEntity3.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.getDes(subject)));
            fEntity3.setFCredit(invoiceApply.getTaxPayable());
            customerList.add(fEntity3);

            BigDecimal cost = returnCost.compareTo(BigDecimal.ZERO) > 0 ? returnCost.negate() : returnCost;
            //主营业务成本-云平台 5401.02
            FEntity fEntity4 = FEntity.addFentity();
            fEntity4.setFExplanation(remark2);
            fEntity4.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.main02.getFNumber()));
            fEntity4.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingdeeCode));
            fEntity4.setFDebit(cost);

            FEntity fEntity5 = FEntity.addFentity();
            fEntity5.setFExplanation(remark2);
            fEntity5.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingDee));
            fEntity5.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.release01.getFNumber()));
            fEntity5.setFCredit(cost);

            customerList.add(fEntity4);
            customerList.add(fEntity5);

            KingDeeBusiness business = new KingDeeBusiness(invoiceApply.getId(), invoiceApply.getNumber(), BusinessType.PlatformCustomerRedInvoice, invoiceApply.getInvoiceTime(), null, invoiceApply.getAccountName());

            KingDeeEntity kingDeeEntity = getKingDeeEntity(customerList, business);
            doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);

        } else {
            //  todo 供应商发票红冲 供应商发票暂时不区分转采还是非转采

            //普通发票
            List<FEntity> ordinary = new ArrayList<>();
            //增值税发票
            List<FEntity> vat = new ArrayList<>();

            String remark3 = "红字发票号：" + invoiceApply.getNumber() + "--" + vendorCompanyName + "(原发票号：" + numbers + ")";
            String remark4 = "红字-供应商订单号：" + invoiceApply.getVoucherId() + "--暂估冲回--" + vendorCompanyName;

            //库存商品-云平台 1405.01
            FEntity fEntity6 = FEntity.addFentity();
            fEntity6.setFExplanation(remark3);
            fEntity6.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.stock01.getFNumber()));
            fEntity6.setFDebit(invoiceApply.getAmount());
            ordinary.add(fEntity6);

            //应付账款-云平台-供应链 2202.03.01
            FEntity fEntity7 = FEntity.addFentity();
            fEntity7.setFExplanation(remark3);
            fEntity7.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0301.getFNumber()));
            fEntity7.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(vendorId));
            fEntity7.setFCredit(invoiceApply.getAmount());
            ordinary.add(fEntity7);


            //库存商品-云平台 1405.01
            FEntity fEntity8 = FEntity.addFentity();
            fEntity8.setFExplanation(remark3);
            fEntity8.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.stock01.getFNumber()));
            fEntity8.setFDebit(pretaxAmount);
            vat.add(fEntity8);

            //应交税费-应交增值税--进项税额转出
            FEntity fEntity9 = FEntity.addFentity();
            fEntity9.setFExplanation(remark3);
            fEntity9.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.tax0104.getFNumber()));
            fEntity9.setFCredit(invoiceApply.getTaxPayable().negate());
            vat.add(fEntity9);

            //应付账款-云平台-供应商  2202.03.01
            FEntity fEntity10 = FEntity.addFentity();
            fEntity10.setFExplanation(remark3);
            fEntity10.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0301.getFNumber()));
            fEntity10.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(vendorId));
            fEntity10.setFCredit(invoiceApply.getTaxPayable().add(pretaxAmount));
            vat.add(fEntity10);

            //4.1 采购暂估冲回
            //借-库存商品-云平台  1405.01
            FEntity fEntity11 = FEntity.addFentity();
            fEntity11.setFExplanation(remark4);
            fEntity11.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.stock01.getFNumber()));
            fEntity11.setFDebit(pretaxAmount.negate());
            vat.add(fEntity11);
            ordinary.add(fEntity11);

            //
            FEntity fEntity12 = FEntity.addFentity();
            fEntity12.setFExplanation(remark4);
            fEntity12.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0302.getFNumber()));
            fEntity12.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(vendorId));
            fEntity12.setFCredit(pretaxAmount.negate());

            vat.add(fEntity12);
            ordinary.add(fEntity12);

            KingDeeBusiness business = new KingDeeBusiness(invoiceApply.getId(), invoiceApply.getNumber(), BusinessType.PlatformSupplierRedInvoice, invoiceApply.getInvoiceTime(), null, invoiceApply.getAccountName());

            if (invoiceApply.getType().equals(KingDeeInvoiceApplyTypeEnum.VAT_ORDINARY)) {

                KingDeeEntity kingDeeEntity = getKingDeeEntity(ordinary, business);

                doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);
            } else {

                KingDeeEntity kingDeeEntity = getKingDeeEntity(vat, business);

                doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);
            }
        }

        log.info("开红字发票生成凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }


    /*开服务费发票生成凭证：/create/fee/invoice*/
    public SingleResponse createFeeInvoiceVoucher(KingDeeServiceFeeInvoice serviceFeeInvoice) {
        log.info("开服务费发票生成凭证  request:{}", serviceFeeInvoice);

        String number = serviceFeeInvoice.getNumber();
        String purchaseInvoiceNumber = serviceFeeInvoice.getPurchaseInvoiceNumber();
        String orgCompanyName = serviceFeeInvoice.getOrgCompanyName();

        String remark = "服务费发票号：" + number + "---采购发票号:" + purchaseInvoiceNumber + "--服务费销售--" + orgCompanyName;
        //组织id
        String organizationId = serviceFeeInvoice.getOrganizationId();
        //价税合计
        BigDecimal amount = serviceFeeInvoice.getAmount();
        //平台费
        BigDecimal pretaxPlatform = serviceFeeInvoice.getPretaxPlatform();
        //服务费
        BigDecimal pretaxInterest = serviceFeeInvoice.getPretaxInterest();
        //税额
        BigDecimal taxPayable = serviceFeeInvoice.getTaxPayable();
        //发票申请单id
        String id = serviceFeeInvoice.getId();

        List<FEntity> fEntities = new ArrayList<>();

        //借：应收账款-云平台-服务费 1122.06.02
        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0602.getFNumber()));
        fEntity1.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(organizationId));
        //价税合计
        fEntity1.setFDebit(amount);
        fEntities.add(fEntity1);

        if (pretaxPlatform != null && pretaxPlatform.compareTo(BigDecimal.ZERO) > 0) {

            //贷：主营业务收入-云平台-平台服务费 5001.06.02
            FEntity fEntity2 = FEntity.addFentity();
            fEntity2.setFExplanation(remark);
            fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.income0602.getFNumber()));
            fEntity2.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(organizationId));
            //平台服务费不含税金额
            fEntity2.setFCredit(pretaxPlatform);
            fEntities.add(fEntity2);
        }

        if (pretaxInterest != null && pretaxInterest.compareTo(BigDecimal.ZERO) > 0) {

            //贷：主营业务收入-云平台-金融服务费 5001.06.03
            FEntity fEntity3 = FEntity.addFentity();
            fEntity3.setFExplanation(remark);
            fEntity3.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.income0603.getFNumber()));
            fEntity3.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(organizationId));
            //金融服务费不含税金额
            fEntity3.setFCredit(pretaxInterest);
            fEntities.add(fEntity3);
        }

        //贷：应交税费-应交增值税-销项税额-6% 2221.01.02.03（6%）
        FEntity fEntity4 = FEntity.addFentity();
        fEntity4.setFExplanation(remark);
        fEntity4.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.tax010203.getFNumber()));
        //税额
        fEntity4.setFCredit(taxPayable);
        fEntities.add(fEntity4);

        //应收账款-云平台-供应商
        FEntity fEntity5 = FEntity.addFentity();
        fEntity5.setFExplanation(remark);
        fEntity5.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0301.getFNumber()));
        fEntity5.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(organizationId));
        fEntity5.setFDebit(amount);
        fEntities.add(fEntity5);

        //应收账款-云平台-服务费
        FEntity fEntity6 = FEntity.addFentity();
        fEntity6.setFExplanation(remark);
        fEntity6.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0602.getFNumber()));
        fEntity6.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(organizationId));
        fEntity6.setFCredit(amount);
        fEntities.add(fEntity6);

        KingDeeBusiness business = new KingDeeBusiness(id, serviceFeeInvoice.getNumber(), BusinessType.PlatformVendorBlueTicket, serviceFeeInvoice.getTime(), null, serviceFeeInvoice.getAccountName());

        KingDeeEntity kingDeeEntity = getKingDeeEntity(fEntities, business);

        doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);

        log.info("开服务费发票生成凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }


    //    开服务费红冲发票生成凭证: /create/fee/red/invoice
    public SingleResponse createFeeRedInvoiceVoucher(KingDeeServiceFeeRedInvoice serviceFeeRedInvoice) {
        log.info("开服务费红冲发票生成凭证  request:{}", serviceFeeRedInvoice);

        //组织id
        String orgId = serviceFeeRedInvoice.getOrgId();
        //价税合计
        BigDecimal amount = serviceFeeRedInvoice.getAmount();
        //未税金融费
        BigDecimal pretaxInterest = serviceFeeRedInvoice.getPretaxInterest();
        //未税平台费
        BigDecimal pretaxPlatform = serviceFeeRedInvoice.getPretaxPlatform();
        //税额
        BigDecimal taxPayable = serviceFeeRedInvoice.getTaxPayable();
        //摘要
        String remark = "采购发票号：" + serviceFeeRedInvoice.getNumber() + " --服务费红冲-- " + serviceFeeRedInvoice.getOrgCompanyName() + "（原发票号：" + serviceFeeRedInvoice.getOldNumber() + "）";

        List<FEntity> fEntities = new ArrayList<>();

        //借：应收账款-云平台-服务费 1122.06.02
        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0602.getFNumber()));
        fEntity1.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(orgId));
        //价税合计
        BigDecimal amountUnAbs = amount.compareTo(BigDecimal.ZERO) > 0 ? amount.negate() : amount;
        fEntity1.setFDebit(amountUnAbs);
        fEntities.add(fEntity1);

        if (null != pretaxInterest && pretaxInterest.compareTo(BigDecimal.ZERO) != 0) {

            //贷：主营业务收入-云平台-平台服务费 5001.06.02
            FEntity fEntity2 = FEntity.addFentity();
            fEntity2.setFExplanation(remark);
            fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.income0602.getFNumber()));
            fEntity2.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(orgId));
            //金融服务不含税金额
            fEntity2.setFCredit(pretaxInterest.compareTo(BigDecimal.ZERO) > 0 ? pretaxInterest.negate() : pretaxInterest);
            fEntities.add(fEntity2);

        }

        if (null != pretaxPlatform && pretaxPlatform.compareTo(BigDecimal.ZERO) != 0) {
            //贷：主营业务收入-云平台-金融服务费 5001.06.03
            FEntity fEntity3 = FEntity.addFentity();
            fEntity3.setFExplanation(remark);
            fEntity3.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.income0603.getFNumber()));
            fEntity3.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(orgId));
            fEntity3.setFCredit(pretaxPlatform.compareTo(BigDecimal.ZERO) > 0 ? pretaxPlatform.negate() : pretaxPlatform);
            fEntities.add(fEntity3);

        }

        //贷：应交税费-应交增值税-销项税额-6%  2221.01.02.03（6%）
        FEntity fEntity4 = FEntity.addFentity();
        fEntity4.setFExplanation(remark);
        fEntity4.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.tax010203.getFNumber()));
        //税额
        fEntity4.setFCredit(taxPayable.compareTo(BigDecimal.ZERO) > 0 ? taxPayable.negate() : taxPayable);
        fEntities.add(fEntity4);


        //应收账款-云平台-供应商
        FEntity fEntity5 = FEntity.addFentity();
        fEntity5.setFExplanation(remark);
        fEntity5.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0301.getFNumber()));
        fEntity5.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(orgId));
        fEntity5.setFDebit(amountUnAbs);
        fEntities.add(fEntity5);


        //应收账款-云平台-服务费
        FEntity fEntity6 = FEntity.addFentity();
        fEntity6.setFExplanation(remark);
        fEntity6.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0602.getFNumber()));
        fEntity6.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(orgId));
        fEntity6.setFCredit(amountUnAbs);
        fEntities.add(fEntity6);

        KingDeeBusiness business = new KingDeeBusiness(serviceFeeRedInvoice.getId(), serviceFeeRedInvoice.getNumber(), BusinessType.PlatformSupplierRedTicket, null, null, serviceFeeRedInvoice.getAccountName());

        KingDeeEntity kingDeeEntity = getKingDeeEntity(fEntities, business);

        doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);

        log.info("开服务费红冲发票生成凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }

    /**
     * 修改发票生成凭证
     * 根据发票申请单ID删除之前的凭证
     * 获取修改后的发票对象调用开票生成凭证方法
     */
    public SingleResponse updateInvoiceVoucher(KingDeeUpdateInvoice updateInvoice) {
        log.info("修改发票生成凭证  request:{}", updateInvoice);

        //todo 这里的业务逻辑有点迷

        //普通票
        KingDeeInvoiceApply iInvoiceApply = updateInvoice.getIInvoiceApply();
        //红票
        KingDeeRedInvoiceApply redInvoiceApply = updateInvoice.getKingDeeRedInvoiceApply();

        if (null != iInvoiceApply) {

            deleteRecordAndUpdate(iInvoiceApply.getId(), BusinessType.PlatformCustomerInvoice, updateInvoice.getAccountName());

            iInvoiceApply.setAccountName(updateInvoice.getAccountName());
            createInvoiceVoucher(iInvoiceApply);

        } else if (null != redInvoiceApply) {

            deleteRecordAndUpdate(redInvoiceApply.getId(), BusinessType.PlatformCustomerRedInvoice, updateInvoice.getAccountName());

            redInvoiceApply.setAccountName(updateInvoice.getAccountName());
            createRedInvoiceVoucher(redInvoiceApply);
        }

        log.info("修改发票生成凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }

    //    取消开票删除凭证: /cancel/invoice
    public SingleResponse cancelInvoiceVoucher(String id) {
        log.info("取消开票删除凭证  request:{}", id);

        //更新记录表 需要先查出来，然后再更新
        //todo JdbcTemplateUtils
        List<RecordVoucher> recordVoucherList = recordVoucherRepository.findByBusinessId(id);

        for (RecordVoucher recordVoucher : recordVoucherList) {
            int del = recordVoucherRepository.del(recordVoucher.getId());
        }


        //SingleResponse<BOList> finds = BoServiceUtils.findListBySimple(ModelConst.T_RECORD_VOUCHER, "business_id", id);
//        if (finds.getData().getTotal() > 0) {
//
//            for (Map<String, Object> data : finds.getData().getData()) {
//                Map<String, Object> updateData = Maps.newHashMap();
//                updateData.put("id", data.get("id"));
//                updateData.put("del", true);
//
//                //todo JdbcTemplateUtils
//                SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_RECORD_VOUCHER, updateData);
//                log.info("取消付款删除凭证 更新记录数据 response:{}", response.getData().getData());
//            }
//        }

        log.info("取消开票删除凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }

    //    取消确认收票删除凭证: /cancel/receive/invoice
    public SingleResponse cancelReceiveInvoiceVoucher(KingDeeDeleteInvoice deleteInvoice) {
        log.info("取消确认收票删除凭证  request:{}", deleteInvoice);
        String id = deleteInvoice.getId();
        String accountName = deleteInvoice.getAccountName();
        if (StringUtils.isNotBlank(id)) {

            //删除收票对应凭证
            deleteRecordAndUpdate(id, BusinessType.PlatformSupplierInvoice, accountName);

            //删除增补对应凭证
            deleteRecordAndUpdate(id, BusinessType.TransactionRecord, accountName);
        }

        log.info("取消确认收票删除凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }

    //    平台增补凭证：/create/supplement
    public SingleResponse createSupplementVoucher(KingDeeTrade trade) {
        log.info("平台增补凭证  request:{}", trade);

        //摘要
        String remark = "发票号码：" + trade.getNumber() + "--补差";
        //增补金额
        BigDecimal amount = trade.getAmount();
        List<FEntity> fEntities = new ArrayList<>();

        //平台供应商增补
        //主营业务成本-云平台 5401.02
        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.main02.getFNumber()));
        fEntity1.setFDetailIdEntity(FDetailIdEntity.addDetailID6("补差"));
        //增补金额
        fEntity1.setFDebit(amount);
        fEntities.add(fEntity1);

        //库存商品-云平台 1405.01
        FEntity fEntity2 = FEntity.addFentity();
        fEntity2.setFExplanation(remark);
        fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.stock01.getFNumber()));
        //增补金额
        fEntity2.setFCredit(amount);
        fEntities.add(fEntity2);

        KingDeeBusiness business = new KingDeeBusiness(trade.getInvoiceId(), null, BusinessType.TransactionRecord, null, null, trade.getAccountName());

        KingDeeEntity kingDeeEntity = getKingDeeEntity(fEntities, business);

        doSaveKingDeeAndRecord(FormEnum.VOUCHER, kingDeeEntity, business);

        log.info("平台增补凭证  业务逻辑处理结束 <<<");
        return SingleResponse.buildSuccess();
    }

    /**
     * 通过平台税率 获取对应的金蝶税率科目
     * 应交税费_应交增值税_销项税额
     *
     * @param taxRate
     */
    public static Integer getTax(BigDecimal taxRate) {
        if (taxRate.compareTo(new BigDecimal("0.10")) == 0) {
            return 19;
        }
        if (taxRate.compareTo(new BigDecimal("0.16")) == 0) {
            return 17;
        }
        if (taxRate.compareTo(new BigDecimal("0.06")) == 0) {
            return 18;
        }
        if (taxRate.compareTo(new BigDecimal("0.13")) == 0) {
            return 20;
        }
        if (taxRate.compareTo(new BigDecimal("0.09")) == 0) {
            return 21;
        }
        return null;
    }


}
